/**
 * upload.js v0.1
 * jQuery Image Upload Plugin
 * @author longfei <feingto@gmail.com>
 * 
 * <input type="file" id="file" name="file" accept="image/jpeg, image/x-png"/>
 * $('#file').UploadImage({
 *     path : "/management/security/user/upload",
 *     cutting : true
 * });
 * 
 * cutting: false
 * <script src="${contextPath }/styles/ajaxfileupload/image.js" type="text/javascript"></script>
 * 
 * cutting : true
 * <link href="${contextPath }/styles/Jcrop/css/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
 * <script src="${contextPath }/styles/Jcrop/js/jquery.Jcrop.js" type="text/javascript"></script>
 */

(function ($) {
	
	$.fn.UploadImage = function (options, callback) {
		
		var opts = (typeof(options) === 'object') ? options : {};
		
		var options = $.extend({
        	path: '',
        	cutting: false
        }, opts);
		
		var fileId = this.attr("id");
		
		this.die().live("change", function() {
			var file = $("#" + fileId).val();
			if (file == null || file == "") {
				alertMsg.error("请选择图片！");
				return false;
			}
			if (!/\.(jpg|jpeg|png)$/.test(file)) {
				alertMsg.error("图片的扩展名必须为：jpg,jpeg,png");
				return false;
			}
			$.ajaxFileUpload({
				url : contextPath + options.path,
				data : {'oldPic' : $('input[name=pic]').val()},
				type : 'post',
				secureuri : false,//一般设置为false
				fileElementId : 'file',
				dataType : 'json',
				success : function(data, status) {
					if (status == "success") {
						if (data.err) {
			       		 	alertMsg.error(data.err);
			                return false;
			            }
						addFile(data.msg);
					}
				},
				error : function (data, status, e) {
					$.each(data, function(i, n) {
		                $("#imageDiv").html("<span>图片加载失败！</span>");
		            });
		        }
			});
			return false;
		});

		function addFile(url) {
			var html = '';
			if (options.cutting) {
				html += '<img id="showPic" src="' + contextPath + url + '" />';
			} else {
				html += '<img src="' + contextPath + url + '" onload="resizeImg(this, 100, 100)" />';
			}
			html += '<input type="hidden" name="pic" value="' + url + '" />';
			/*html += '<p>';
			html += '<input type="button" value="缩小" onclick="zoomOut()">';
			html += '<input type="button" value="放大" onclick="zoomIn()">';*/
			$("#imageDiv").html(html);
			if (options.cutting) {
				$('#showPic').Jcrop({
					onChange : showCoords,
					onSelect : showCoords,
					minSize : [60, 60],
					maxSize : [160, 160],
					setSelect : [0, 0, 160, 160]
				});
			}
		}

		function showCoords(c){
			$("input[name=x]").val(c.x);
			$("input[name=y]").val(c.y);
			$("input[name=w]").val(c.w);
			$("input[name=h]").val(c.h);
		};
	};
	
}(jQuery));